package org.snail.chat.service.chatchain.chain;


import lombok.NonNull;
import org.apache.log4j.Logger;
import org.snail.chat.service.chatchain.dao.ChatCreateOrUpdateDAO;
import org.snail.chat.service.chatchain.regular.HandlerRegular;
import org.snail.dept.bean.TreeNode;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 群组责任链接口
 */
public abstract class ChatCreateOrUpdateHandler {

    private final Logger LOGGER = Logger.getLogger(ChatCreateOrUpdateHandler.class);

    private HandlerRegular handlerRegular;

    //下一级责任链
    public ChatCreateOrUpdateHandler handler;

    //设置Chat创建更新规则
    public void setHandlerRegular(HandlerRegular handlerRegular) {
        this.handlerRegular = handlerRegular;
    }

    //设置Chat创建更新规则
    public HandlerRegular getHandlerRegular() {
        return this.handlerRegular;
    }

    //设置下一级责任链
    public void setSuccessor(ChatCreateOrUpdateHandler handler) {
        this.handler = handler;
    }

    //执行责任链
    public void doChatCreateOrUpdateHandler(TreeNode treeNode, Map<String, ChatCreateOrUpdateDAO> chatCreateOrUpdateDAOMap) throws Exception {

        doCreateOrUpdate(treeNode, chatCreateOrUpdateDAOMap);
        if (null != handler) {
            handler.doChatCreateOrUpdateHandler(treeNode, chatCreateOrUpdateDAOMap);
        }
    }

    /**
     * 具体责任链逻辑
     *
     * @param treeNode                 树
     * @param chatCreateOrUpdateDAOMap 部门id map
     */
    public abstract void doCreateOrUpdate(TreeNode treeNode, Map<String, ChatCreateOrUpdateDAO> chatCreateOrUpdateDAOMap) throws Exception;

    /**
     * 要么从map中获取对象，要么添加相关属性至map0
     *
     * @param treeNode                 树
     * @param chatCreateOrUpdateDAOMap 部门id map
     */
    protected ChatCreateOrUpdateDAO getChatCreateOrUpdateDAO(@NonNull TreeNode treeNode, @NonNull Map<String, ChatCreateOrUpdateDAO> chatCreateOrUpdateDAOMap) {
        ChatCreateOrUpdateDAO chatCreateOrUpdateDAO ;
        String id = treeNode.getId();   //获取树中的id
        if (chatCreateOrUpdateDAOMap.containsKey(id)) {
            chatCreateOrUpdateDAO = chatCreateOrUpdateDAOMap.get(id);
        } else {
            chatCreateOrUpdateDAO = new ChatCreateOrUpdateDAO();
        }
        chatCreateOrUpdateDAOMap.put(id, chatCreateOrUpdateDAO);
        return chatCreateOrUpdateDAO;
    }

    /**
     * 添加Manager列表到需要添加
     *
     * @param chatCreateOrUpdateDAO
     * @param userIdList
     * @return
     */
    protected void addUserChatCreateOrUpdateDAO(ChatCreateOrUpdateDAO chatCreateOrUpdateDAO, List<String> userIdList) {
        //添加Manager列表到需要添加
        if (null!=chatCreateOrUpdateDAO && null!=chatCreateOrUpdateDAO.getUseridlist()) {
            chatCreateOrUpdateDAO.getUseridlist().addAll(userIdList);
        } else {
            Set<String> userIdSet = new HashSet<String>();
            userIdSet.addAll(userIdList);
            chatCreateOrUpdateDAO.setUseridlist(userIdSet);
        }
    }

}
